package cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon;

import cn.iocoder.yudao.module.crossborder.platform.enums.PlatformTypeEnum;
import cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon.client.AmazonApiClient;
import cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon.config.AmazonPlatformConfig;
import cn.iocoder.yudao.module.crossborder.platform.service.provider.base.BasePlatformProvider;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Amazon平台提供商实现
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class AmazonPlatformProvider extends BasePlatformProvider {

    @Resource
    private AmazonPlatformConfig amazonPlatformConfig;

    @Resource
    private AmazonApiClient amazonApiClient;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public PlatformTypeEnum getPlatformType() {
        return PlatformTypeEnum.AMAZON;
    }

    @Override
    public boolean validateConfig(Object config) {
        log.info("验证Amazon平台配置");

        try {
            if (config == null) {
                log.warn("Amazon平台配置为空");
                return false;
            }

            Map<String, Object> configMap;
            if (config instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> tempMap = (Map<String, Object>) config;
                configMap = tempMap;
            } else if (config instanceof String) {
                configMap = objectMapper.readValue((String) config,
                    new TypeReference<Map<String, Object>>() {});
            } else {
                log.warn("Amazon平台配置格式不支持: {}", config.getClass());
                return false;
            }

            // 验证必要的配置项
            if (!validateRequiredFields(configMap)) {
                return false;
            }

            // 验证API连接
            if (!validateApiConnection(configMap)) {
                return false;
            }

            log.info("Amazon平台配置验证通过");
            return true;

        } catch (Exception e) {
            log.error("验证Amazon平台配置失败", e);
            return false;
        }
    }

    @Override
    public void initializePlatform(Object config) {
        log.info("初始化Amazon平台");

        try {
            if (!validateConfig(config)) {
                throw new RuntimeException("Amazon平台配置验证失败");
            }

            // 刷新配置缓存
            amazonPlatformConfig.refreshCache();

            // 初始化API客户端
            initializeApiClient(config);

            // 验证平台连接
            if (!isHealthy()) {
                log.warn("Amazon平台健康检查失败");
            }

            log.info("Amazon平台初始化完成");

        } catch (Exception e) {
            log.error("初始化Amazon平台失败", e);
            throw new RuntimeException("初始化Amazon平台失败", e);
        }
    }

    @Override
    public boolean isHealthy() {
        try {
            // 1. 检查平台配置是否存在且启用
            if (!amazonPlatformConfig.isEnabled()) {
                log.warn("Amazon平台未启用");
                return false;
            }

            // 2. 检查API基础URL是否可访问
            String apiBaseUrl = amazonPlatformConfig.getApiBaseUrl("NA");
            if (apiBaseUrl == null || apiBaseUrl.trim().isEmpty()) {
                log.warn("Amazon API基础URL未配置");
                return false;
            }

            // 3. 尝试调用Amazon API进行健康检查
            try {
                // 调用一个简单的API端点进行健康检查
                Map<String, Object> healthResponse = amazonApiClient.get("/health", null, null);
                if (healthResponse != null) {
                    log.debug("Amazon API健康检查通过");
                } else {
                    log.debug("Amazon API健康检查无响应，但连接正常");
                }
            } catch (Exception e) {
                log.warn("Amazon API健康检查失败: {}", e.getMessage());
                // API调用失败不一定意味着平台不健康，可能是权限问题
            }

            log.debug("Amazon平台健康状态正常");
            return true;
        } catch (Exception e) {
            log.error("Amazon平台健康检查失败", e);
            return false;
        }
    }

    // ==================== 私有方法 ====================

    /**
     * 验证必要的配置字段
     */
    private boolean validateRequiredFields(Map<String, Object> configMap) {
        // 检查必要的配置项
        String[] requiredFields = {"clientId", "clientSecret", "region"};

        for (String field : requiredFields) {
            if (!configMap.containsKey(field) || configMap.get(field) == null) {
                log.warn("Amazon配置缺少必要字段: {}", field);
                return false;
            }
        }

        // 验证区域代码
        String region = (String) configMap.get("region");
        if (!isValidRegion(region)) {
            log.warn("Amazon配置包含无效的区域代码: {}", region);
            return false;
        }

        return true;
    }

    /**
     * 验证API连接
     */
    private boolean validateApiConnection(Map<String, Object> configMap) {
        try {
            String region = (String) configMap.get("region");
            String apiBaseUrl = amazonPlatformConfig.getApiBaseUrl(region);

            // 简单的连接测试
            if (apiBaseUrl == null || !apiBaseUrl.startsWith("https://")) {
                log.warn("Amazon API基础URL格式无效: {}", apiBaseUrl);
                return false;
            }

            return true;
        } catch (Exception e) {
            log.error("验证Amazon API连接失败", e);
            return false;
        }
    }

    /**
     * 初始化API客户端
     */
    private void initializeApiClient(Object config) {
        try {
            // TODO: 根据配置初始化Amazon API客户端
            log.debug("Amazon API客户端初始化完成");
        } catch (Exception e) {
            log.error("初始化Amazon API客户端失败", e);
            throw new RuntimeException("初始化Amazon API客户端失败", e);
        }
    }

    /**
     * 验证区域代码是否有效
     */
    private boolean isValidRegion(String region) {
        if (region == null || region.trim().isEmpty()) {
            return false;
        }

        String[] validRegions = {"NA", "EU", "FE"};
        for (String validRegion : validRegions) {
            if (validRegion.equalsIgnoreCase(region.trim())) {
                return true;
            }
        }

        return false;
    }

}
